from es import playsound
from playerlib import getPlayer
from gamethread import delayedname, cancelDelayed
from superdice.superdice import registerRoll, unregisterRoll, registerAbility, unregisterAbility, players, rollStrings
from superdice.libs.playerStrings import stringsManager
from superdice.libs.diceConfigs import configFile

def es_map_start(ev):
    cancelDelayed('_superdice_roll_jetpack')
    loopJetpack()
    cfgData.execute()

def unload():
    cancelDelayed('_superdice_roll_jetpack')
    unregisterAbility(plusJetpack, minusJetpack)
    unregisterRoll(diceRoll)

def player_spawn(ev):
    userid = ev['userid']
    players[userid]['jetpack'] = False
    players[userid]['jeton'] = False
    players[userid]['jetfuel'] = 0

def player_disconnect(ev):
    player_spawn(ev)

def loopJetpack():
    for userid in players:
        if not players[userid]['jetpack']:
            continue

        if not players[userid]['jeton']:
            if players[userid]['jetfuel'] < int(fuel):
                players[userid]['jetfuel'] += 1

        else:
            if players[userid]['jetfuel']:
                getPlayer(userid).jetpack = 1
                players[userid]['jetfuel'] -= 1

            if not players[userid]['jetfuel']:
                players[userid]['jeton'] = False
                getPlayer(userid).jetpack = 0
                playsound(userid, 'weapons/mortar/mortar_explode1.wav', 1.0)

        rollStrings.rightTextString(userid, 'showfuel', {'fuel':players[userid]['jetfuel']})

    delayedname(1, '_superdice_roll_jetpack', loopJetpack, ())

def plusJetpack(userid, args):
    userid = str(userid)
    if not players[userid]['jetpack'] or players[userid]['jeton'] or not players[userid]['jetfuel']:
        return

    players[userid]['jeton'] = True
    getPlayer(userid).jetpack = 1
    playsound(userid, 'weapons/mortar/mortar_explode3.wav', 1.0)

def minusJetpack(userid, args):
    userid = str(userid)
    if not players[userid]['jetpack'] or not players[userid]['jeton']:
        return

    players[userid]['jeton'] = False
    getPlayer(userid).jetpack = 0
    playsound(userid, 'weapons/mortar/mortar_explode1.wav', 1.0)

def diceRoll(userid, player, eplayer):
    players[userid]['jetpack'] = True
    players[userid]['jetfuel'] = int(fuel)

cfgData = configFile('dice_jetpack')
fuel = cfgData.cvar('superdice_cfg_jetpack_fuel', 5, 'How much fuel does the player have? (hint: fuel = seconds)')
cfgData.write()
cfgData.execute()

registerAbility(plusJetpack, minusJetpack)

cancelDelayed('_superdice_roll_jetpack')
loopJetpack()

registerRoll(diceRoll, 'jetpack')
